import { Sequelize } from 'sequelize';
import {
  Component,
  ComponentProp,
  ComponentExample,
  ComponentImport,
} from './Component.js';
import {
  Template,
  ComponentCache,
  PerformanceMetric,
} from './Template.js';
import {
  CallLog,
  UsageStat,
} from './CallLog.js';

/**
 * 初始化所有数据模型
 * @param sequelize Sequelize实例
 * @returns 初始化后的模型对象
 */
export function initializeModels(sequelize: Sequelize) {
  // 初始化模型
  const models = {
    Component: Component.initModel(sequelize),
    ComponentProp: ComponentProp.initModel(sequelize),
    ComponentExample: ComponentExample.initModel(sequelize),
    ComponentImport: ComponentImport.initModel(sequelize),
    Template: Template.initModel(sequelize),
    ComponentCache: ComponentCache.initModel(sequelize),
    PerformanceMetric: PerformanceMetric.initModel(sequelize),
    CallLog: CallLog.initModel(sequelize),
    UsageStat: UsageStat.initModel(sequelize),
  };

  // 建立模型关联关系
  setupAssociations(models);

  return models;
}

/**
 * 设置模型之间的关联关系
 */
function setupAssociations(models: any) {
  // Component 与其子表的一对多关系
  models.Component.hasMany(models.ComponentProp, {
    foreignKey: 'component_id',
    as: 'props',
    onDelete: 'CASCADE',
  });

  models.Component.hasMany(models.ComponentExample, {
    foreignKey: 'component_id',
    as: 'examples',
    onDelete: 'CASCADE',
  });

  models.Component.hasMany(models.ComponentImport, {
    foreignKey: 'component_id',
    as: 'imports',
    onDelete: 'CASCADE',
  });

  // 反向关联
  models.ComponentProp.belongsTo(models.Component, {
    foreignKey: 'component_id',
    as: 'component',
  });

  models.ComponentExample.belongsTo(models.Component, {
    foreignKey: 'component_id',
    as: 'component',
  });

  models.ComponentImport.belongsTo(models.Component, {
    foreignKey: 'component_id',
    as: 'component',
  });
}

// 导出所有模型类型
export {
  Component,
  ComponentProp,
  ComponentExample,
  ComponentImport,
  Template,
  ComponentCache,
  PerformanceMetric,
  CallLog,
  UsageStat,
};

// 导出属性接口
export type {
  ComponentAttributes,
  ComponentCreationAttributes,
  ComponentPropAttributes,
  ComponentPropCreationAttributes,
  ComponentExampleAttributes,
  ComponentExampleCreationAttributes,
  ComponentImportAttributes,
  ComponentImportCreationAttributes,
} from './Component';

export type {
  TemplateAttributes,
  TemplateCreationAttributes,
  ComponentCacheAttributes,
  ComponentCacheCreationAttributes,
  PerformanceMetricAttributes,
  PerformanceMetricCreationAttributes,
} from './Template';

export type {
  CallLogAttributes,
  CallLogCreationAttributes,
  UsageStatAttributes,
  UsageStatCreationAttributes,
} from './CallLog';